import { JwtService } from '@nestjs/jwt';
import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { Observable } from 'rxjs';

@Injectable()
export class LoginGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
  ){}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log('检查登录状态的guard ===========>')
    const request: Request = context.switchToHttp().getRequest();
    const token = request.header('authorization') || '';
    console.log('authorization', token);
    
    if(!token) {
      throw new UnauthorizedException('用户没有登录！！！');
    }
    
    try {
      const info = this.jwtService.verify(token);
      (request as any).user = info.user;
      return true;
    } catch(e) {
      throw new UnauthorizedException('登录token失效,请重新登录！！！');
    }
  }
}
